from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional

app = FastAPI()

# 数据模型
class User(BaseModel):
    id: Optional[int] = None
    name: str
    email: str

# 模拟数据库
users_db: List[User] = []

# 获取所有用户
@app.get("/users", response_model=List[User])
def get_users():
    return users_db

# 获取单个用户
@app.get("/users/{user_id}", response_model=User)
def get_user(user_id: int):
    for user in users_db:
        if user.id == user_id:
            return user
    raise HTTPException(status_code=404, detail="User not found")

# 创建用户
@app.post("/users", response_model=User, status_code=201)
def create_user(user: User):
    user.id = len(users_db) + 1
    users_db.append(user)
    return user

# 更新用户
@app.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, updated_user: User):
    for index, user in enumerate(users_db):
        if user.id == user_id:
            updated_user.id = user_id
            users_db[index] = updated_user
            return updated_user
    raise HTTPException(status_code=404, detail="User not found")

# 删除用户
@app.delete("/users/{user_id}", status_code=204)
def delete_user(user_id: int):
    global users_db
    users_db = [user for user in users_db if user.id != user_id]
    return None
